package com.ly.mpayment.persist.service.matchingstrategy;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.*;
import com.ly.mpayment.persist.service.downproductlog.IDownProLogService;
import com.ly.mpayment.persist.service.timer.ProductPriceService;
import com.ly.mpayment.persist.service.timer.ProductPriceUpService;
import com.ly.mpayment.persist.service.timer.ProductTimerService;
import com.ly.mpayment.persist.service.timer.ProductTimerUpService;
import com.ly.mpayment.persist.service.upshoppro.IUpShopProService;
import com.ly.mpayment.persist.service.user.IUserService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ly.mpayment.persist.hibernate.Page;
import com.ly.mpayment.persist.service.AbstractService;
import com.ly.mpayment.persist.service.downshopproduct.IDownShopProductService;
import org.springframework.util.CollectionUtils;

@Service
public class MatchingStrategyServiceImpl extends AbstractService<MatchingStrategy, Serializable> implements IMatchingStrategyService{


	@Autowired
	IDownShopProductService productService;

	@Autowired
	IUpShopProService upProductService;

	@Autowired
	IDownProLogService logService;

	@Autowired
	IUserService userService;

	@Autowired
	private ProductTimerService timerService;

	@Autowired
	private ProductPriceService productPriceService;

	@Autowired
	private ProductPriceUpService productPriceUpService;

	@Autowired
	private ProductTimerUpService productTimerUpService;



	/**
	 * 检查产品是否已经匹配了上游如果是则更新上游信息，如果不是则添加
	 * @param match
	 * @param product
	 * @return
	 */
	@Override
	public boolean addMatchingstrategy(MatchingStrategy match,DownShopProduct product) {
		if(match != null){
			MatchingStrategy  matchs = this.findByDownUuidUp(match.getDownUser().getUseruuid(),match.getProvinceuuid(),
					match.getOperatoruid(),match.getBusuuid(),product.getDownprouuid(),match.getUpUser().getUseruuid());
			if(matchs != null){
				matchs.setUpUser(match.getUpUser());
				matchs.setStatus(product.getDownfacevalue());
				matchs.setRemark(match.getRemark());
				this.updateEntity(matchs);
			}else{
				this.saveOrUpdate(match);
			}
			product.setAuto(Config.autoStrategy[1]);
			this.productService.updateProduct(product);
			return true;
		}
		return false;
	}

	/**
	 * 批量添加产品多匹配
	 * 如果 upuuid 不为空  upprouuids 为空 则默认切换当前所有产品渠道
	 * @param json
	 * @return
	 */
	@Override
	public String addMatchingstrategy(JSONObject json, User user) {
		//downprouuid 调整为数组
		JSONArray pros = json.getJSONArray("downprouuid");
		String upprouuids = "";
		for(int i = 0 ; i < pros.size() ; i++){
			upprouuids += "'"+pros.getString(i)+"',";
		}
		if(!upprouuids.equals("")){
			upprouuids = upprouuids.substring(0,upprouuids.lastIndexOf(","));
		}
		BigInteger count = this.productService.findProductStrategyCount(upprouuids);
		if(count.intValue() != pros.size()){
			return ResultMessage.getFailt("产品状态不正常,请检查");
		}
		String result = "";

		for(int i = 0 ; i < pros.size() ; i++){
			json.put("prouuid",pros.getString(i));
			result = matchProduct(json,user);
			if(!result.equals("")){
				break;
			}
		}
		if(!result.equals("")){
			return result;
		}
		return ResultMessage.getSucceed("操作成功");
	}
	private String matchProduct(JSONObject json, User user){
		DownShopProduct product = this.productService.findProductStrategy(json.getString("prouuid"));
		if(product != null){

			boolean temp = false;

			JSONArray ups = json.getJSONArray("upprouuids");

			if(!StringUtils.isBlank(json.getString("upuuid")) && ups.size() == 0){
				//查询当前产品的所有匹配模式 修改为选中后的上游产品
				List<DownShopProduct> productList = this.productService.findByUuidDownProduct(product.getUser().getUseruuid(),
						product.getProvincialInformation().getProvinceuuid(),product.getOperators().getOperatoruid(),product.getBusinessType().getBusuuid());
				if(!CollectionUtils.isEmpty(productList)){
					for (int i = 0; i < ups.size(); i++) {
						UpShopProduct upShopProduct = upProductService.findByUpShopProduct(json.getString("upuuid"),
								product.getProvincialInformation().getProvinceuuid(),product.getOperators().getOperatoruid(),
								product.getBusinessType().getBusuuid(),product.getDownfacevalue(),product.getCityName());
						if(upShopProduct == null){
							temp = true;
							break;
						}
					}
					if(temp){
						return ResultMessage.getFailt("上游客户产品"+product.getDownfacevalue()+"面值不存在,请先添加");
					}

					//为空就新增 不为空就修改
					for (int i = 0; i < productList.size(); i++) {
						DownShopProduct productUp = productList.get(i);
						//先删除所有匹配产品
						if(!this.deleteMatechDownProduct(product.getDownprouuid())){
							//return ResultMessage.getFailt("删除失败");
						}
						// 先删除在新增
						MatchingStrategy strategy = new MatchingStrategy();
						UpShopProduct upShopProduct = upProductService.findByUpShopProduct(json.getString("upuuid"),
								productUp.getProvincialInformation().getProvinceuuid(),productUp.getOperators().getOperatoruid(),
								productUp.getBusinessType().getBusuuid(),productUp.getDownfacevalue(),productUp.getCityName());
						if(!upShopProduct.getUpfacevalue().equals(productUp.getDownfacevalue())){
							continue;
						}
						//查询上游是否有指定 业务类型 运营商 面值 省份 产品如果没有则失败
						strategy.setUpUser(new User(json.getString("upuuid")));
						strategy.setDownUser(productUp.getUser());
						strategy.setRemark(upShopProduct);
						strategy.setOperatoruid(productUp.getOperators().getOperatoruid());
						strategy.setProvinceuuid(productUp.getProvincialInformation().getProvinceuuid());
						strategy.setCityName(json.getString("cityName"));
						strategy.setBusuuid(productUp.getBusinessType().getBusuuid());
						strategy.setStatus(productUp.getDownfacevalue());
						strategy.setDownprouuid(productUp.getDownprouuid());
						strategy.setOrderSort(i+1);
						this.addMatchingstrategy(strategy,productUp);
						User userUp = this.userService.findByUserid(json.getString("upuuid"));

						logService.addLog(productUp,user,productUp.getUser().getUsername(),userUp.getUsername());
					}
					if(temp){
						return ResultMessage.getFailt("上游客户产品"+product.getDownfacevalue()+"面值不存在,请先添加");
					}
				}
				return "";
			}else{
				//先删除所有匹配产品
				if(!this.deleteMatechDownProduct(product.getDownprouuid())){
				//	return ResultMessage.getFailt("删除失败");
				}
				for (int i = 0; i < ups.size(); i++) {
					//String useruuid,String provinceuuid,String operatoruid,String busuuid,String productUuid,String cityName

					MatchingStrategy strategy = new MatchingStrategy();
					UpShopProduct upShopProduct = this.upProductService.findProductAndFaceValue(ups.getJSONObject(i).getString("upprouuid"),
							product.getDownfacevalue());
					if(upShopProduct == null){
						temp = true;
						break;
//						return ResultMessage.getFailt("上游客户产品"+product.getDownfacevalue()+"面值不存在,请先添加");
					}
					if(!upShopProduct.getUpfacevalue().equals(product.getDownfacevalue())){
						continue;
					}
					strategy.setUpUser(upShopProduct.getUser());
					strategy.setDownUser(product.getUser());
					strategy.setRemark(upShopProduct);
					strategy.setOperatoruid(product.getOperators().getOperatoruid());
					strategy.setProvinceuuid(product.getProvincialInformation().getProvinceuuid());
					strategy.setCityName(json.getString("cityName"));
					strategy.setBusuuid(product.getBusinessType().getBusuuid());
					strategy.setDownprouuid(product.getDownprouuid());
					strategy.setStatus(product.getDownfacevalue());
					strategy.setOrderSort(i+1);
					addMatchingstrategy(strategy,product);
					logService.addLog(product,user,product.getUser().getUsername(),upShopProduct.getUser().getUsername());
				}
				if(temp){
					return ResultMessage.getFailt("上游客户产品"+product.getDownfacevalue()+"面值不存在,请先添加");
				}
				return "";
			}
		}
		return ResultMessage.getFailt("操作失败");
	}

	@Override
	public boolean addMatchingstrategy(MatchingStrategy match) {
		if(match != null){
			MatchingStrategy  matchs = this.findByDownUuid(match.getDownUser().getUseruuid(),match.getProvinceuuid(),match.getOperatoruid(),match.getBusuuid());
			if(matchs != null){
				matchs.setUpUser(match.getUpUser());
				this.updateEntity(matchs);
			}else{
				this.saveOrUpdate(match);
			}

			//更新所有产品为手动匹配 按省份 运营商 转为手动产品
			List<DownShopProduct> products = this.productService.findByUuidDownProduct(match.getDownUser().getUseruuid(),match.getProvinceuuid(),match.getOperatoruid(),match.getBusuuid());
			if(products != null && !products.isEmpty()){
				for(int i = 0 ; i < products.size(); i++){
					products.get(i).setAuto(Config.autoStrategy[1]);
					this.productService.updateProduct(products.get(i));
				}
			}
			return true;
		}
		return false;
	}

	@Override
	public List<MatchingStrategy> findByDownUuid(String useruuid,String provinceuuid,String operatoruid,String busuuid,String downprouuid,String upporductid) {
		String temp = "";
		if(!StringUtils.isBlank(upporductid)){
			String str [] = upporductid.split(",");
			for(int i = 0 ; i < str.length; i++){
				temp += "'"+str[i]+"',";
			}
		}
		return this.find("select m from MatchingStrategy m left join fetch m.upUser left join fetch m.remark r where m.downUser.useruuid = ? and m.provinceuuid = ? and " +
				" m.operatoruid = ? and m.busuuid = ? and m.downprouuid = ? "+ (StringUtils.isBlank(upporductid) ? "" : " and m.remark not in ("+temp.substring(0,temp.length() -1)+") ")+"order by r.discount, m.orderSort ", useruuid,provinceuuid,operatoruid,busuuid,downprouuid);
	}
	@Override
	public MatchingStrategy findByDownUuid(String useruuid,String provinceuuid,String operatoruid,String busuuid) {
		return this.findOneObject("select m from MatchingStrategy m left join fetch m.upUser where m.downUser.useruuid = ? and m.provinceuuid = ? and " +
				" m.operatoruid = ? and m.busuuid = ?  ", useruuid,provinceuuid,operatoruid,busuuid);
	}

	@Override
	public MatchingStrategy findByDownUuidUp(String useruuid,String provinceuuid,String operatoruid,String busuuid,String downprouuid, String upuseruuid) {
		return this.findOneObject("select m from MatchingStrategy m left join fetch m.upUser where m.downUser.useruuid = ? and m.provinceuuid = ? and " +
				" m.operatoruid = ? and m.busuuid = ? and m.downprouuid = ? and m.upUser.useruuid = ?  ", useruuid,provinceuuid,operatoruid,busuuid,downprouuid,upuseruuid);
	}

	@Override
	public MatchingStrategy findByDownUuidUp(String provinceuuid, String operatoruid, String busuuid,  String upuseruuid) {
		return this.findOneObject("select m from MatchingStrategy m left join fetch m.upUser where  m.provinceuuid = ? and " +
				" m.operatoruid = ? and m.busuuid = ? and m.upUser.useruuid = ?  ",provinceuuid,operatoruid,busuuid,upuseruuid);
	}

	@Override
	public MatchingStrategy findByDownUuidUpFace(String provinceuuid, String operatoruid, String busuuid,  String upuseruuid,String faceValue,String downprouuid) {
		if(StringUtils.isBlank(faceValue)){
			return null;
		}
		return this.findOneObject("select m from MatchingStrategy m left join fetch m.upUser where  m.provinceuuid = ? and " +
				" m.operatoruid = ? and m.busuuid = ? and m.upUser.useruuid = ? and ( m.status = ? or m.status = 1) and m.downprouuid = ? ",provinceuuid,operatoruid,busuuid,upuseruuid,faceValue,downprouuid);
	}


	@Override
	public boolean updateMatchingstrategy(MatchingStrategy match) {
		if(match != null){
			this.saveOrUpdate(match);
			return true;
		}
		return false;
	}

	@Override
	public MatchingStrategy findById(String id) {
		return this.findUnique("select m from MatchingStrategy m where m.matchinguuid = ?", id);
	}

	@Override
	public Page<MatchingStrategy> findPageMatchingstrategy(Map<String, Object> parameters, int start, int pageSize) {
		return this.findPageByNamed("select m from MatchingStrategy m  order by m.matchname", parameters, start, pageSize);
	}

	@Override
	public boolean deleteStrategy(MatchingStrategy match) {
		if(match != null){
			this.delete(match);
			return true;
		}
		return false;
	}

	@Override
	public MatchingStrategy findByProduct(String productUuid) {
		return this.findUnique("select m from MatchingStrategy m where m.downShopProduct.downprouuid = ?", productUuid);
	}

	/**
	 * 添加删除 产品 已经存在的所有策略
	 */
	@Override
	public boolean deleteMatech(String useruuid,String provinceuuid,String operatoruid,String busuuid,String productUuid,String cityName) {
		if(!StringUtils.isBlank(productUuid)){
			this.deleteQuery(" delete from matchingstrategy where downprouuid = '"+
					productUuid+"' and downuuid = '"+useruuid+"' and provinceuuid = '"+provinceuuid+"'  and operatoruid ='"+operatoruid+"' " +
					" and busuuid = '"+busuuid+"' " + (StringUtils.isBlank(cityName) ? "" : " and city_name ='"+cityName+"'"));
			return true;
		}
		return false;
	}

	@Override
	public boolean deleteMatechUp(String useruuid,String provinceuuid,String operatoruid,String busuuid,String productUuid,String cityName,String facevalue) {
		if(!StringUtils.isBlank(productUuid)){
			this.deleteQuery(" delete from matchingstrategy where downprouuid = '"+
					productUuid+"' and upuuid = '"+useruuid+"' and provinceuuid = '"+provinceuuid+"'  and operatoruid ='"+operatoruid+"' " +
					" and busuuid = '"+busuuid+"' and status = '"+facevalue+"' " + (StringUtils.isBlank(cityName) ? "" : " and city_name ='"+cityName+"'"));
			return true;
		}
		return false;
	}
	@Override
	public boolean deleteMatechDown(String useruuid,String provinceuuid,String operatoruid,String busuuid,String productUuid,String cityName,String facevalue) {
		if(!StringUtils.isBlank(productUuid)){
			String deltesql = " delete from matchingstrategy where downprouuid = '"+
					productUuid+"' and downuuid = '"+useruuid+"' and provinceuuid = '"+provinceuuid+"'  and operatoruid ='"+operatoruid+"' " +
					" and busuuid = '"+busuuid+"' and status = '"+facevalue+"' " + (StringUtils.isBlank(cityName) ? "" : " and city_name ='"+cityName+"'");
			this.deleteQuery(deltesql);
			return true;
		}
		return false;
	}

	@Override
	public boolean deleteMatechDownProduct(String productUuid) {
		if(!StringUtils.isBlank(productUuid)){
			String deltesql = " delete from matchingstrategy where downprouuid = '"+productUuid+"'";
			return this.getSession().createSQLQuery(deltesql).executeUpdate() > 0;
		}
		return false;
	}



//	@Override
//	public MatchingStrategy findByManualDownFlow(String downFlowId) {
//		return this.findUnique("select m from MatchingStrategy m left join fetch m.includesProducts i left join fetch i.upshopproduct u where m.downRechargeFlow.downorderuuid = ? order by u.upfacevalue ", downFlowId);
//	}

	@Override
	public MatchingStrategy findByProductFetchInclu(String downUuid) {
		return this.findUnique(" select m from MatchingStrategy m left join fetch m.includesProducts i left join fetch i.upshopproduct u where u.status = 1 and m.downShopProduct.downprouuid = ?  ", downUuid);
	}

	@Override
	public MatchingStrategy findByProductFetchIncluDown(String downUuid,String upProUuid) {
		return this.findUnique(" select m from MatchingStrategy m left join fetch m.upUser where  m.downprouuid = ? and m.remark = ?", downUuid,upProUuid);
	}


	@Override
	public int downCount(String downprouuid) {
		return Integer.valueOf(this.getSession().createSQLQuery(" SELECT count(m.downprouuid) from matchingstrategy m where m.downprouuid = '"+downprouuid+"'").uniqueResult().toString());
	}

	@Override
	public int upSumUpUser(String downprouuid) {
		return Integer.valueOf(this.getSession().createSQLQuery("select sum(CASE up.repeat_num WHEN 0 THEN 1 ELSE up.repeat_num END) from upshopinfo up where up.useruuid in (select u.upuuid from matchingstrategy u where u.downprouuid = '"+downprouuid+"')" ).uniqueResult().toString());
	}

	@Override
	public String queryStrategyPage(JSONObject json, int start, int pageSize) {
		Page pa = new Page();
		pa.setStart(start);
		pa.setPageSize(pageSize);
		Page page = PaginationUtil.queryPaginationSQL("select * from ("+getSql(json)+") temp order by downname ,order_sort desc,upname", pa, this.getSession());
		List lists = page.getResult();
		if(lists != null){
			JSONArray array = JsonUtils.getJSONARRAY();
			for(int i = 0 ; i < lists.size();i++){
				JSONObject obj = JsonUtils.getJSONOBJCT();
				Object [] object = (Object[]) lists.get(i);
				obj.put("status", object[0] == null ? "" : object[0].toString());
				obj.put("orderSort", object[1] == null ? "" : object[1].toString());
				obj.put("userUp", object[2].toString());
				obj.put("userDown", object[3].toString());
				obj.put("productName",  object[4] == null ? 0 : object[4].toString());
				obj.put("upName", object[5] == null ? 0 : object[5].toString());
				obj.put("provinceName", object[6] == null ? 0 :object[6].toString());
				obj.put("operatorName",  object[7] == null ? 0 : object[7].toString());
				obj.put("matchinguuid",object[8] == null ? 0 :  object[8].toString());
				obj.put("downprouuid",object[9] == null ? 0 :  object[9].toString());
				obj.put("busname",object[10] == null ? 0 :  object[10].toString());
				obj.put("updiscount",object[11] == null ? 0 :  object[11].toString());
				obj.put("downdiscount",object[12] == null ? 0 :  object[12].toString());
				array.add(obj);
			}
			page.setResult(array);
			return JsonUtils.convertObjectToJson(page);
		}
		return JsonUtils.getJSONARRAY().toString();
	}

	public String getSql(JSONObject jsonObject){
		String sql = " SELECT m.status,m.order_sort,(select u.username from user u where u.useruuid = m.upuuid ) as upname,us.username as downname,dp.product_name,up.product_name as upProdName," +
				" p.provincename,o.operatorname,m.matchinguuid," +
				" m.downprouuid,bt.busname,up.discount as updiscount,dp.discount as downdiscount from matchingstrategy m  " +
				" inner join user us on us.useruuid = m.downuuid" +
				" inner join downshopproduct dp on dp.downprouuid = m.downprouuid" +
				" inner join upshopproduct up on up.upprouuid = m.remark" +
				" inner join provincialinformation p on p.provinceuuid = m.provinceuuid" +
				" inner join operators o on o.operatoruid = m.operatoruid" +
				" inner join businesstype bt on bt.busuuid = m.busuuid where 1 = 1 ";
		if(jsonObject.containsKey("userUp")  && !StringUtils.isBlank(jsonObject.getString("userUp"))){
			sql += " and m.upuuid = '" + jsonObject.getString("userUp")+"' ";
		}
		if(jsonObject.containsKey("userDown")  && !StringUtils.isBlank(jsonObject.getString("userDown"))){
			sql += " and m.downuuid = '" + jsonObject.getString("userDown")+"' ";
		}
		if(jsonObject.containsKey("status")  && !StringUtils.isBlank(jsonObject.getString("status"))){
			sql += " and m.`status` = '" + jsonObject.getString("status")+"' ";
		}
		if(jsonObject.containsKey("busuuid")  && !StringUtils.isBlank(jsonObject.getString("busuuid"))){
			sql += " and m.busuuid = '"+jsonObject.getString("busuuid")+"' ";
		}
		if(jsonObject.containsKey("operatoruid")  && !StringUtils.isBlank(jsonObject.getString("operatoruid"))){
			sql += " and m.operatoruid = '"+jsonObject.getString("operatoruid")+"' ";
		}
		if(jsonObject.containsKey("provinceuuid") && !StringUtils.isBlank(jsonObject.getString("provinceuuid"))){
			sql += " and m.provinceuuid = '"+jsonObject.getString("provinceuuid")+"' ";
		}
		return sql;
	}

	/**
	 * json数组
	 * "downprouuid","matchinguuids:[]"
	 *  matchinguuids:{matchinguuid:'',orderSort:1}
	 * @param json
	 * @return
	 */
	@Override
	public boolean updateStrategy(JSONObject json) {
		MatchingStrategy matchingStrategy = this.findById(json.getString("matchinguuid"));
		if(matchingStrategy != null){
			matchingStrategy.setOrderSort(json.getInt("orderSort"));
			return  this.saveOrUpdate(matchingStrategy) != null;
		}
		return false;
	}


	/**
	 * 定时调价
	 *
	 * @param json
	 * @return
	 */
	@Override
	public String batchProductTimer(JSONObject json,User user) {
		ProductTimer timer = new ProductTimer();
		timer.setAfterDiscount(BigUtil.getBigDecimal(json.getString("afterdiscount")));
		timer.setBeforeDiscount(BigUtil.getBigDecimal(json.getString("beforediscount")));
		timer.setBusname(json.getString("busname"));
		timer.setCreateTime(DateUtils.getNowDate());
		timer.setCreateUser(user.getUsername());
		timer.setCreateUserId(user.getUseruuid());
		timer.setDownName(json.getString("downName"));
		timer.setExecuteTime(DateUtils.parseDate(json.getString("executeTime")));
		timer.setNote(json.getString("note"));
		timer.setOperator(json.getString("operator"));
		timer.setProvince(json.getString("province"));
		timer.setStatus(0);
		timer.setEnabled(false);
		timerService.saveProduct(timer);
		//保存到产品明细表
		JSONArray array = json.getJSONArray("batchTimer");
		if(array != null && array.size() > 0){
			for(int i = 0 ; i < array.size() ; i ++){
				JSONObject pro = array.getJSONObject(i);
				ProductPrice price = new ProductPrice();
				DownShopProduct product = this.productService.findById(pro.getString("downprouuid"));
				price.setAfterDiscount(BigUtil.getBigDecimal(json.getString("afterdiscount")));
				price.setBeforeDiscount(product.getDiscount());
				price.setDownName(product.getUser().getUsername());
				price.setUserId(product.getUser());
				price.setProductId(product);
				price.setProId(timer);
				price.setProductName(product.getProductName());
				price.setBeforeValue(product.getDiscountAmount());
				price.setAfterValue(product.getPrice().multiply(BigUtil.getBigDecimal(json.getString("afterdiscount"))));
				productPriceService.saveProductPrice(price);
			}
		}
		return ResultMessage.getSucceed();
	}

	@Override
	public boolean findByCount(String upprouuid) {
		return BigDecimal.valueOf(this.findLong("SELECT count(*) from MatchingStrategy d  where d.remark.upprouuid = ?",upprouuid)).intValue() > 0;
	}

	@Override
	public boolean findByDownCount(String downprouuid) {
		return BigDecimal.valueOf(this.findLong("SELECT count(*) from MatchingStrategy d  where d.downprouuid = ?",downprouuid)).intValue() > 0;
	}

	@Override
	public String batchProductTimerUp(JSONObject json, User login) {
		ProductTimerUp timer = new ProductTimerUp();
		timer.setAfterDiscount(BigUtil.getBigDecimal(json.getString("afterdiscount")));
		timer.setBeforeDiscount(BigUtil.getBigDecimal(json.getString("beforediscount")));
		timer.setBusname(json.getString("busname"));
		timer.setCreateTime(DateUtils.getNowDate());
		timer.setCreateUser(login.getUsername());
		timer.setCreateUserId(login.getUseruuid());
		timer.setUpName(json.getString("upName"));
		timer.setExecuteTime(DateUtils.parseDate(json.getString("executeTime")));
		timer.setNote(json.getString("note"));
		timer.setOperator(json.getString("operator"));
		timer.setProvince(json.getString("province"));
		timer.setStatus(0);
		timer.setEnabled(false);
		productTimerUpService.saveProduct(timer);
		//保存到产品明细表
		JSONArray array = json.getJSONArray("batchTimer");
		if(array != null && array.size() > 0){
			for(int i = 0 ; i < array.size() ; i ++){
				JSONObject pro = array.getJSONObject(i);
				ProductPriceUp price = new ProductPriceUp();
				UpShopProduct product = this.upProductService.findById(pro.getString("upprouuid"));
				price.setAfterDiscount(BigUtil.getBigDecimal(json.getString("afterdiscount")));
				price.setBeforeDiscount(product.getDiscount());
				price.setUpName(product.getUser().getUsername());
				price.setUserId(product.getUser());
				price.setProductId(product);
				price.setProId(timer);
				price.setProductName(product.getProductName());
				price.setBeforeValue(product.getDiscountAmount());
				price.setAfterValue(product.getPrice().multiply(BigUtil.getBigDecimal(json.getString("afterdiscount"))));
				productPriceUpService.saveProductPrice(price);
			}
		}
		return ResultMessage.getSucceed();
	}
}
